package com.wzh.glsc.search.service.Impl;

import com.alibaba.fastjson.JSON;
import com.wzh.common.to.es.SkuEsModel;
import com.wzh.glsc.search.config.MallElasticSearchConfig;
import com.wzh.glsc.search.constant.EsConstant;
import com.wzh.glsc.search.service.ProductSaveService;
import lombok.extern.slf4j.Slf4j;
import org.elasticsearch.action.bulk.BulkRequest;
import org.elasticsearch.action.bulk.BulkResponse;
import org.elasticsearch.action.index.IndexRequest;
import org.elasticsearch.client.RestHighLevelClient;
import org.elasticsearch.common.xcontent.XContentType;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.io.IOException;
import java.util.Arrays;
import java.util.List;
import java.util.stream.Collectors;

/**
 * @author xiaoming
 * @PackageName:com.wzh.glsc.search.service.Impl
 * @ClassName:@{NAME}
 * @Description:
 * @date:@{DATE}@{TIME}
 */
@Slf4j
@Service("productSaveService")
public class ProductSaveServiceImpl implements ProductSaveService {

    @Autowired
    private RestHighLevelClient restHighLevelClient;

    @Override
    public Boolean productStatusUp(List<SkuEsModel> skuEsModels) throws IOException {
        //批量处理对象
        BulkRequest bulkRequest = new BulkRequest();
        for (SkuEsModel skuEsModel : skuEsModels) {
            //单个请求条件 EsConstant.PRODUCT_INDEX是索引id,自定义
            IndexRequest request = new IndexRequest(EsConstant.PRODUCT_INDEX);
            request.id(skuEsModel.getSkuId().toString());
            String str = JSON.toJSONString(skuEsModel);
            request.source(str, XContentType.JSON);
            //将单个请求条件保存到批量处理中
            bulkRequest.add(request);
        }
        ;
        //接收批量处理返回值的数据
        BulkResponse bulk = restHighLevelClient.bulk(bulkRequest, MallElasticSearchConfig.COMMON_OPTIONS);
        //如果出现错误,这里是调用结果集中的hasFailures
        Boolean b = bulk.hasFailures();
        //循环保存成功的数据id
        List<String> collect = Arrays.asList(bulk.getItems()).stream().map(item -> {
            return item.getId();
        }).collect(Collectors.toList());
        if (b) {
            log.error("商品上架错误:{}", collect);
        } else {
            log.info("上架成功", collect);
        }
        return b;

    }
}
